import { store } from "@/store";
import axios from "axios";

axios.interceptors.request.use((config)=>{
   if(store.token && config.headers){
    config.headers.Authorization =  `Bearer ${store.token}`
   }
  return config
})

axios.interceptors.response.use((response)=>{

 return response
},err=>{
  const code = err.response.data.errors[0].extensions.code
  console.log(err.response,'response');
  if(err.response.status === 401 || err.response.status === 403){
    localStorage.removeItem('token')
    location.reload()
  }
  // INVALID_CREDENTIALS
  return Promise.reject(err)
})

let baseurl = ''
// let baseurl = `http://${location.hostname}:5000`
// if (import.meta.env.PROD) {
//   baseurl = `http://${location.host}`
//   // wssurl = 'ws://service-ee3bfr8j-1300311241.sh.apigw.tencentcs.com/release'
// }
export function request(url, { data, method }: { data?: Record<string, string | number | boolean>, method: string }) {
  return Promise.reject()
  url = baseurl + url
  const obj = {
    method: method,
    headers: { Authorization: `Bearer ${store.token}` }
  }
  if (method === 'post') {
    obj.body = JSON.stringify(data)
    obj.headers['Content-Type'] = 'application/json'
  }
  if (method === 'get' && data) {
    let paramsArray: string[] = [];
    //拼接参数
    Object.keys(data).forEach(key => paramsArray.push(key + '=' + data[key]))
    if (url.search(/\?/) === -1) {
      url += '?' + paramsArray.join('&')
    } else {
      url += '&' + paramsArray.join('&')
    }
  }

  return fetch(url, obj)
}